                                                     //===========================================================================
// mediaPlayer.js
// Steampunk Media Player Widget  1.0.10
// Written and Steampunked by: Dean Beedell
// Dean.beedell@lightquick.co.uk
//===========================================================================

/*
   When a folder is selected, the contents of that folder are read into an array. That
   array is the playlist. When files are dragged and dropped onto the playlist area then
   the array is replaced. Single files are currently played without using the playlist.

*/

/*global mainWindow, cableWheelSet, cable, pipes, bell, indicatorRed, speaker, bar,
	sliderSet, percentTextShadow, percentText, resize, mainScreen, setmenu, settooltip, buildVitality,
	checkTimer, sliderSetClicked:true, volumePlaque, volumePlaqueX, volumeTick,
	volumeNoTick
*/

/*properties
    Width, data, event, extractFile, hOffset, height, hidden, hoffset, interval,
    match, mute, muteIntervalPref, onMouseMove, plaquepref, platform, replace,
    scrollDelta, maxWidthPref, soundpref, split, src, ticking, toFixed, toLowerCase,
    toString, value, visible, voffset, volume, width, winverPref
*/

// 1.0.4
// created sourceforge page
// added drag and drop of files, single file or folder.
// added restriction to the drive root folders
// added restriction to 10,000 file playlists.
// added support for .flv','.avi','.mp4','.mpg','.m4a file types
// added 5 favourite folders to play to the menu
// added read the play list and display a chunk of the tracks
// added hover over effects as per the widget vault
// added setting of the play list tooltips
// added some checks when playing a folder to see if it exists
// store the current play list location in hidden prefs - playlistLocationPref

// 1.0.5
// added the volume control through the up and down keys
// added the next/previous track control through the N and K keys
// added the play/pause track control through the space bar
// added the track advance/retard control through the left/right keys
// scroll the current track in the playlist
// highlight the currently selected track in the playlist
// double clicking on a selected track in the playlist now plays the track.
// highlight the chosen track in grey.
// add the capability to determine which chunk is being displayed
// playlist can resize, box, text and buttons
// added next/previous buttons to select chunks, the code to select the next chunk works
// added chain to select the playlist
// selected track to rotate in the play list, same as mouseover
// fixed bug whereby the positiontimer would be kicked off during next/back tracks, timer is now turned off during keypress
// fixed bug to highlight the currently selected trackwhen on subsequent pages of the playlist
// added the code to select the last tracks in the very last chunk when you select the end of the play list
// now counts the valid tracks correctly, previously was over-estimating
// double clicking on the folder name will open that folder
// after shuffle button, re-read the playlist
// start and end buttons for the playlist
// add the functionality to change font as per the weather widget
// add the functionality to change fontsize as per the weather widget
// update function descriptions
// width of playlist text to be fixed
// fixed the scaling flattening the font size
// fixed playlist exit button moves when resized
// single click on a track highlights it
// determine exactly what is 100% with regard to overall size
// when a previous folder is selected via the menu, the playlist display should be updated
// when a track is single-clicked the scrolling is not removed from the currently playing track
// allow drag and drop onto the play list
// create a routine to clear the playlist
// when a new folder is selected the folder name does not change immediately, needs a restart
// highlight the currently running track when new chunk selected
// placed the music folders in their own preference group

// 1.06
// if the folder does not exist - play the last folder/playlist
// if the folder exists but there is nothing to play then deal with that condition
// when a new folder is selected the playlist does not display immediately, needs a restart
// test the saving and re-use of previously played folders
// dragging and dropping onto the playlist area does not yet display the new playlist - tested, it does
// fixed bug in showing the playlist on small groups of files dragged/dropped or in a folder,no longer generates an error
// ".mpeg",".mp4",".mpg added to the possible file types that can be played
// add a file limit capture to the recursive folder search that is done at the beginning, new function to count
// playfolder function tests for valid types in the same way as the other functions
// when opening an alternate folder the chunk list needs to be reset to 1
// change the displayed default folder when dragging/dropping a set of files to the folder location where the files came from
// when the widget restarts it is picking up the wrong folder name, now checks two locations
// opening a new folder fails from the speaker but works from the menu
// mousewheel scrolling on the playlist should roll a chunk - fixed
// fixed the final bugs with the recursive file count
// shuffle isn't shuffling - fixed
// pulling chain causes the playlist to be re-generated so a shuffle playlist is unshuffled
// added save and open buttons for the playlist
// additional button to clear the play list
// shuffle not working on start up
// fixed some bugs trying to set slider position when there is no currently playing media for the WMplayer
// add image to tell users that the reading of folders is underway..
// added save and open functionality saving as XML
// add roll over buttons for the bottom set
// fix the clicking on a track name sometimes does not pull up the google listing
// fixed bugs with opening and saving play list files
// removed duplicate code calling the playlist twice on startup
// fixed bug where only a partial playlist is being read, not reading the filecount from the XML and then not using it.
// fix to the currently highlighted track bug
// remove the wpl remote playlist types that seem to be unsupported in WMP
// test with non-existent folder - works OK
// test with empty folder - works OK
// test with my music folder - works OK
// test with a CD - plays
// CD does not show the list of tracks in the play list
// fix the track number display when unshuffled
// fix the track number display when a CD is loaded
// explain the black box that can be shown when accessing a large series of files on a slow system - instructions added
// when playing a CD, the stuck position code might need to be ignored as CDs do pause when initialising.
// playing a CD - needs to show the CD/album title
// audio CD track tooltips added
// audio CD title tooltips added
// restart after playing a CD shows an empty track list due to chosen folder pointing to a CD drive
// opening a playlist file after playing a CD does not update the list of tracks in the play list
// audio CD second page not showing correctly, still showing first page items
// when shuffling a CD it restores the last used folder information
// added a routine to wipe the play list that helps when debugging.
// reset the page number when opening a CD.
// reset the page number when opening a new playlist.
// shuffling a CD does not yet work, shuffled the code a little!
// added support for .m4a file types
// dragging a single file does not update the playlist
// after dragging a single file a multiple file drop does not show on the playlist

// 1.0.7

// created Xwidget version 2.0 RC from 1.0.7
// autoplay disable was broken, always started playing, now awaits a track selection or play button to be pressed
// drag and drop on the playlist adds to existing list rather than replace altogether
// uppercase file suffixes, eg .MP3 need to be catered for
// handles CDs when selected using the file explorer
// fixed bug in playing a single track, it refused to play it at all when autoplay was disabled
// valid types was not functioning for single file selection, did not display any media files at all

// 1.0.8

// tooltips for all items
// checks for valid folder before playing
// when saving a playlist, checks it is an XML file.
// default music folder should be C:\Users\Public\Music
// selecting a CD from the folder menu works from the menu too.
// unknown file types such as .aac if Windows will not play the filetype then pop up an error message.
//
// 1.0.9
//
// the playbutton  needs to be modified to respect the startup flag - done
// hints enabled/disabled correctly on demand - done
// resizing when using the CTRL key on the playlist now works
// tested using codecs to recognise the latest file types - done
// checks CD drive present for non-CD equipped systems
// synch. with the Xwidget version
// when you drop a second folder after dropping a single file, it does not update the playlist, a refresh required
// replaced the resizing code, removing a lot of variable declarations and using a more elegant function to resize.
// the function that checks whether the track is stuck needs to be modified to respect the startup flag
// dragging and dropping a folder does not always update the folder name

// TBD in 1.0.10
// added a message when a root folder is selected.
// added a preference to allow the bottom tracklist buttons to be retained on screen.
//
// YWE revisit the countDirContents

// add some pipes/cables to the play list to connect the player
// add the clear playlist functionality
// bundle the Centurion SF light font with the widget

// allow deletion of a track from the playlist via a right click context menu
// allow deletion of a track from the playlist via a pop up metal/red X when the mouse hovers over a track
// allow tracks to be dragged to different locations in the playlist

var Scale = Number(preferences.maxWidthPref.value) / 100;

var perc = 0;
var fontDefault = preferences.popupPanelFontSizePref.value;

//resizing variables
var mainWindowwidthDefault = mainWindow.width;
var mainWindowheightDefault = mainWindow.height;
var chainvoffsetDefault =  chain.voffset;     // retained

var buzzer 		= "Resources/buzzer.mp3";
var zzzz 		= "Resources/zzzz.mp3";
var tingingSound 	= "Resources/ting.mp3";
var currIcon 		= "Resources/volume-dock.png";
var lock 		= "Resources/lock.mp3";
var winding 		= "Resources/winding.mp3";
var creturn 		= "Resources/creturn.mp3";
var keypress 		= "Resources/keypress.mp3";

var WMPlayer = COM.createObject("wmplayer.ocx");
var thePlayList;
var IsPlaylist;
var PlayIndex = 0;
var trackIndex = 0;

COM.connectObject(WMPlayer, "WMP_");
WMPlayer.settings.setMode("loop", false);
WMPlayer.settings.autoStart = false;
WMPlayer.settings.mute = false;
//WMPlayer.currentPlaylist.count;

var CDROM = WMPlayer.cdromCollection;
var cdRomNo = 0;
var CDROMcount = CDROM.count;
var isAudioCD = false;

var isFolder = false;
var filePlayList = 0;
var currentFile;
var playListfileCount = 0;
var sliderSetClicked = false;
var positionSliderClicked = false;
var drvCnt = 0;
var playerState = "none";

var storedWMPpos = 0;
var stuckCycleCount = 0;
var zeroCycleCount = 0;
var playOverride = false;

var trackNumber = new Array(11);
var trackName = new Array(11);
var fullTrackName = new Array(11);
var chunkSize = 11;
var chunkIndex = 0;
var debugFlg = preferences.debugflgPref.value;
var idxFile = 0;
var chosenFolder = "";
var fileCountLimit = 20000;
var path = null;

// this list has to be doubled to take into account accidental renaming of suffixes to capitalised state
// the list is passed to in-built functions where the input filename cannot be handled by js code
// so the list is simply uppercase-d and doubled up.
var validTypesLcase = [".mpeg",".mp4",".m4a",".mpg",".flv",".mp3",".aac",".wav",".wma",".aif",".aiff",".au",".snd"];
var validTypesUcase =  String.prototype.toUpperCase.apply(validTypesLcase).split(",");
var validTypes =  validTypesLcase + "," + validTypesUcase;
var file_extension = "";

var createNewList = 0; // this determines whether you can drag/drop or not.
var trackFailCnt = 0;
var filePlayedWell = 0;
preferences.errorMessagesPref.Value = "enabled"; // at the mo' reset whenever the widget is restarted

var busyCounter = 1;

//===========================================
// end variable declarations
//===========================================

//===========================================
// this function runs on startup
//===========================================
function startup() {
    if (debugFlg == 1) {print ("%-I-INFO, startup")};
    print (validTypes);

    startupFlg = 1;
    resize(); 		// resize if required
    mainScreen(); 	// check the widget is on-screen
    createLicence(mainWindow);     // create the licence window
    startVolume(); // check the start volume levels
    checkPath();
    setmenu(); // build the menu
    settooltip(); // build the tooltips
    buildVitality(currIcon, perc, WMPlayer.settings.mute); // build the dock vitality
    checkLocked();       // set the widget lock status if pinned
    // the saved shuffle status is set during the check of the ply state below
    checkAutoPlayState(); // set the autoplay state - if autoplay then reads the default folder
    if (preferences.playListPref.value == "enabled") {
       playlistFrame.visible = true;
     } else {
        playlistFrame.visible = false;
    }
	// update the playlist only when not shuffled as the same routine is called after the re-shuffling
	if (preferences.shuffleStatePref.value != "enabled") {
		updatePlayList();
	}
    setFont();

    busyStop();
}
//=====================
//End function
//=====================

//===========================================
// Function
//===========================================
function busyStop() {
    print("%myStatusProc - stopping the busy timer ");
    busyTimer.ticking=false;
    busy.visible=false;
    busyBlur.visible=false;
}
//=====================
//End function
//=====================

//===========================================
// Function
//===========================================
function setFont() {
    if (debugFlg == 1) {print ("%-I-INFO, setFont")};
    playListTitle.font = preferences.popupPanelFont.value;
    playListPage.font = preferences.popupPanelFont.value;
    playListText0.font = preferences.popupPanelFont.value;
    playListText1.font = preferences.popupPanelFont.value;
    playListText2.font = preferences.popupPanelFont.value;
    playListText3.font = preferences.popupPanelFont.value;
    playListText4.font = preferences.popupPanelFont.value;
    playListText5.font = preferences.popupPanelFont.value;
    playListText6.font = preferences.popupPanelFont.value;
    playListText7.font = preferences.popupPanelFont.value;
    playListText8.font = preferences.popupPanelFont.value;
    playListText9.font = preferences.popupPanelFont.value;
    playListText10.font = preferences.popupPanelFont.value;
    playListText11.font = preferences.popupPanelFont.value;
}
//=====================
//End function
//=====================

//===========================================
// Functions for use with runCommand
//===========================================
function quotePath(path) {
	return "\"" + convertPathToPlatform(path).replace(/\"/g, "\\\"") + "\"";
}
//=====================
//End functions
//=====================

//===========================================
// Functions for use with runCommand
//===========================================
function escapePath(path) {
	return path.replace(/([\W])/g, '\\$1');
}
//=====================
//End functions
//=====================

//=========================================================
// Function to stretch the cable
//=========================================================
function stretchCable() {
//now calculate the stretch of the cable
    cable.hOffset = sliderSet.hOffset + (sliderSet.width);
    cable.Width = (cableWheelSet.hOffset + cableWheelSet.width) - (cable.hOffset);
}
//=====================
//End function
//=====================

//===========================================
// function to test whether the media player is muted
//===========================================
function testmute() {
    if (debugFlg == 1) {print ("%-I-INFO, testmute")};
    log("running start volume " + WMPlayer.settings.mute);
    if (WMPlayer.settings.mute) {
        indicatorRed.src = "Resources/indicatorRed.png";
    } else {
        indicatorRed.src = "Resources/indicatorGreen.png";
    }
}
//=====================
//End function
//=====================

//=========================================================
// Function to determine the media layer sound levels at startup
//=========================================================
function startVolume() {
    if (debugFlg == 1) {print ("%-I-INFO, startVolume")};
    testmute();
    //autoplay levels
       //set the last used volume level in percent from the slider.
       preferences.volumePref.value = preferences.autoPlayVolumePref.value;
    //default levels (stored)
    WMPlayer.settings.volume = preferences.volumePref.value;
    //print("WMPlayer.settings.volume "+ WMPlayer.settings.volume);
    sliderSet.hOffset = ((bar.hoffset + (25 * Scale)) + ((WMPlayer.settings.volume * 1.05) * Scale));
    perc = parseInt(WMPlayer.settings.volume, 10);
    percentTextShadow.data = perc + "%";
    percentText.data = perc + "%";
    stretchCable();

}
//=====================
//End function
//=====================

//===========================================
// Function to set the media player volume
//===========================================
function setVol() {
    //if (debugFlg == 1) {print ("%-I-INFO, setVol")};

    WMPlayer.settings.volume = perc;
    preferences.volumePref.value = perc;
    //if (WMPlayer.settings.mute) muteIt();
}
//=====================
//End function
//=====================

//===========================================
// Function to determine what happens when the mouse is pressed on the position slider
//===========================================
function positionSliderOnMouseDown() {
//      log("Running function sliderSetOnMouseDown");
    positionSliderClicked = true;
//      log("Leaving function sliderSetOnMouseDown " +clicked);
}
//=====================
//End function
//=====================

//===========================================
// Function to determine what happens when the mouse is lifted from the position slider
//===========================================
function positionSliderOnMouseUp() {
    if (positionSliderClicked === true) {
        positionSliderClicked = false;
        positionSlider.onMouseMove = null;
    }
//log("Running function sliderSetOnMouseUp clicked is now "+ clicked);
}
//=====================
//End function
//=====================

//===========================================
// Function to slide the graphical position slider
//===========================================
function positionSliderOnMouseMove() {
  if(positionSliderClicked)
  {
    positionSlider.hOffset = system.event.hOffset - (25 * Scale);
    constrainPositionSlider();
  }
}
//=====================
//End function
//=====================

//===================================
// function to move/constrain the track position slider
//===================================
function constrainPositionSlider() {
    var positionSliderRightmost,
        positionSliderLeftMost,
        positionSliderSliderwidth,
        positionSliderCurrpos,
        positionSliderperc;

//determine slider travel limits
    positionSliderRightmost = (120 * Scale) + positionSlider.width ; //positionSliderLeftMost limit
    //print("positionSliderRightmost "+positionSliderRightmost);
    //print("positionSlider.width "+positionSlider.width);
    positionSliderLeftMost = (55 * Scale) ; // positionSliderRightmost limit
    //print("positionSliderLeftMost "+positionSliderLeftMost);
    if (positionSlider.hOffset >= positionSliderRightmost) { //568
        positionSlider.hOffset = positionSliderRightmost;
    }
    if (positionSlider.hOffset <= positionSliderLeftMost) { //262
        positionSlider.hOffset = positionSliderLeftMost;
    }
//calculate the percentage
    positionSliderSliderwidth = positionSliderRightmost - positionSliderLeftMost;
    positionSliderCurrpos = positionSlider.hOffset - positionSliderLeftMost;
    positionSliderperc = parseInt((positionSliderCurrpos / positionSliderSliderwidth) * 100, 10);
    if (positionSliderperc < 0) {
        positionSliderperc = 0;
    }
    WMPlayer.controls.currentPosition = (positionSliderperc * WMPlayer.currentMedia.duration) /100;
}
//=====================
//End function
//=====================

//===================================
// function called by the sliderTimer on a small interval, it sets the graphical slider position automatically to correspond with the Windows Media player actual position
//===================================
function setSliderPosition() {
    var positionSliderRightmost,
        positionSliderLeftMost,
        positionSliderSliderwidth,
        positionSliderCurrpos,
        positionSliderperc,
        wmplayerPerc;
    //print ("setSliderPosition counting");

		if(!positionSliderClicked && WMPlayer.currentMedia )
        {
            positionSliderRightmost = (120 * Scale) + positionSlider.width ; //positionSliderLeftMost limit
            positionSliderLeftMost = (55 * Scale) ; // positionSliderRightmost limit
            positionSliderSliderwidth = positionSliderRightmost - positionSliderLeftMost;

            wmplayerPerc =  (WMPlayer.controls.currentPosition / WMPlayer.currentMedia.duration) *100;
            positionSlider.hOffset = ((positionSliderSliderwidth * wmplayerPerc)/100) + positionSliderLeftMost;
            // print ("positionSliderSliderwidth " +positionSliderSliderwidth);
            // print ("positionSliderLeftMost " +positionSliderLeftMost);
            // print ("wmplayerPerc " +wmplayerPerc);
            // print ("positionSlider.hOffset " +positionSlider.hOffset);
        }
}
//=====================
//End function
//=====================

//===================================
// function called by the position timer every 2 secs to check the current media player position and select the next track when this track ends
//===================================
function checkPosition() {
         var triggerNExt = 0;
         // To allow for WMP's bad handling of flv files.
         // if the currentPosition value has not changed for two cycle, select the next track

         // increment the stuck count
         if (storedWMPpos == WMPlayer.controls.currentPosition) {
           stuckCycleCount = stuckCycleCount + 1;
         }

         if ( filePlayedWell == 0 && WMPlayer.controls.currentPosition == 0 ) {
            if (debugFlg == 1) {print ("Found Beginning of Track");};
                print("%startup - busyTimer started");
                busyTimer.ticking=true;
         }

         if ( filePlayedWell == 1 && WMPlayer.controls.currentPosition == 0 ) {
            if (debugFlg == 1) {print ("Found End of Track");};
                print("%startup - busyTimer started");
                busyTimer.ticking=true;
         }
         // if the file has been successfully played but the file is stuck at the beginning of the track
         if ( filePlayedWell == 1 && stuckCycleCount >=2) {
                triggerNExt = 1;
                stuckCycleCount = 0;
		if (isAudioCD == false) {
                      // something later
		}
         }


         // if the file hasn't yet been played and the cycle is stuck then the codec isn't installed
         if ( storedWMPpos == WMPlayer.controls.currentPosition && filePlayedWell == 0 && stuckCycleCount >=2) {
                positionTimer.ticking = false; // pause the position timer to prevent multiple messages
                triggerNExt = 1;
                stuckCycleCount = 0;
		if (isAudioCD == false) {
                     if (preferences.errorMessagesPref.Value == "enabled")  {
                            var answer = alert("Trying to play this file " + WMPlayer.URL + String.fromCharCode(13) + String.fromCharCode(13) + "However, your version of Windows does not recognise this type of file ." + file_extension + String.fromCharCode(13) + "Search internet for codecs that will support this file type? ", "Open Browser Window", "No Thanks");
                            if (answer === 1) {
		                 openURL("https://www.google.co.uk/?gws_rd=ssl#q=windows+media+player+codecs+for+"+file_extension);
                            }
                     }
                     trackFailCnt = trackFailCnt + 1;
                     if (preferences.errorMessagesPref.Value == "enabled" && trackFailCnt >= 2 ) {
	                          var answer = alert("Do you want me to stop these annoying error messages? ", "Yes please!", "No Thanks")
                        if (answer === 1) {
		                     preferences.errorMessagesPref.Value = "disabled";
                        } else {
                           trackFailCnt = 0;
                        }
                     }
		}
		positionTimer.ticking = true;  // restart the position timer to allow future checks
         } else {
           if (debugFlg == 1) {print ("storedWMPpos "+storedWMPpos)};
           if (debugFlg == 1) {print ("WMPlayer.controls.currentPosition "+WMPlayer.controls.currentPosition)};
         	 if (debugFlg == 1) {print ("stuckCycleCount "+stuckCycleCount)};
         	 if (debugFlg == 1) {print ("filePlayedWell "+filePlayedWell)};
         }
         // check the value of the WMP current position and store it
         storedWMPpos = WMPlayer.controls.currentPosition;
         if (storedWMPpos > 0) {
             filePlayedWell = 1;
         };

         //if (debugFlg == 1) {print ("checking every 2 secs ")};

         // the WMP end of track is indicated by a zero position but obviously the start is too -
         // so we have a short delay before we select the next track
         // if the trigger has been set then select the next track
         if ( triggerNExt == 1  ) {
		if (debugFlg == 1) {print ("WMPlayer.controls.currentPosition "+WMPlayer.controls.currentPosition)};
		if (debugFlg == 1) {print ("zeroCycleCount "+zeroCycleCount)};
		if (debugFlg == 1) {print ("triggerNExt "+triggerNExt)};

                zeroCycleCount = 0;
                WMPlayer.controls.currentPosition = 0;
                positionTimer.ticking = true;
                //if playing a single track set the buttons
              	if (playerState == "single")  {
                    playButton.visible=true;
                    pauseButton.visible=false;
                } else {
                    // only skip the track if not a CD, CDs can be slow to initialise
                    if (isAudioCD == false) {
        		       // cause the next track to play if a folder selected
                               if (PlayIndex+1 < playListfileCount ) {
                                        PlayIndex++;
                               } else {
                                        PlayIndex = 0;
                               }
                               filePlayedWell = 0;
                               if (debugFlg == 1) {print ("Automatically playing next track "+WMPlayer.URL)};
                    }
                    if (debugFlg == 1) {print ("Playmedia Call no. 1")};
                    PlayMedia(PlayIndex );
                    positionTimer.ticking = true;
                    busyStop();
            }
         } else {
             stuckcyclecount = 0;
             //busyStop();
         }
         zeroCycleCount = zeroCycleCount + 1;
}
//=====================
//End function
//=====================

//===========================================
// Function to constrain the main volume slider and set the media player volume accordingly
//===========================================
function moveSliderSet() {
    var rightmost,
        leftmost,
        sliderwidth,
        currpos;

//determine slider travel limits
    rightmost = bar.hOffset + bar.width - (100 * Scale); //leftmost limit
    leftmost = bar.hOffset + (25 * Scale); // rightmost limit
    if (sliderSet.hOffset >= rightmost) { //568
        sliderSet.hOffset = rightmost;
    }
    if (sliderSet.hOffset <= leftmost) { //262
        sliderSet.hOffset = leftmost;
    }
    stretchCable();

//calculate the percentage
    sliderwidth = rightmost - leftmost;
    currpos = sliderSet.hOffset - leftmost;
    perc = parseInt((currpos / sliderwidth) * 100, 10);
    if (perc < 0) {
        perc = 0;
    }
    setVol();

    percentTextShadow.data = perc + "%";
    percentText.data = perc + "%";
    buildVitality(currIcon, perc, WMPlayer.settings.mute); // build the dock vitality
    //if (preferences.soundpref.value === "enabled") {
        //play(zzzz, false);
    //}
    //print("sliderSet.hOffset "+sliderSet.hOffset);
}
//=====================
//End function
//=====================

//===========================================
// Function to slide the volume slider according to mouse scrollwheel position
//===========================================
function sliderSetOnMouseWheel() {
    var delta = system.event.scrollDelta;
    if (!system.event.ctrlKey) {  //only if the user is not selecting the control key
      if (delta !== 0) {
          if ( preferences.mouseWheelVolumePref.value == "right" ) {
            sliderSet.hOffset += (delta*2) * Scale;
          } else {
            sliderSet.hOffset -= (delta*2) * Scale;
          }
          moveSliderSet();
      }
    setVol();
    }
}
//=====================
//End function
//=====================

//===========================================
// Function to slide the volume slider according to mouse position when moving
//===========================================
function sliderSetOnMouseMove() {
  if(sliderSetClicked)
  {
    sliderSet.hOffset = system.event.hOffset - (35 * Scale);
    moveSliderSet();
  }
}
//=====================
//End function
//=====================

//===========================================
// Function to determine what happens when the mouse is pressed on the size slider
//===========================================
function sliderSetOnMouseDown() {
//      log("Running function sliderSetOnMouseDown");
    sliderSetClicked = true;
//      log("Leaving function sliderSetOnMouseDown " +clicked);
}
//=====================
//End function
//=====================

//===========================================
// Function to determine what happens when the mouse is lifted from the size slider
//===========================================
function sliderSetOnMouseUp() {
    setVol();
    if (sliderSetClicked === true) {
        sliderSetClicked = false;
        sliderSet.onMouseMove = null;
    }
//log("Running function sliderSetOnMouseUp clicked is now "+ clicked);
}
//=====================
//End function
//=====================

//===================================
// function to select the URL for WMP given a path
//===================================
function FileMedia(path) {
	this.sourceURL = path;
}
//=====================
//End function
//=====================

//===================================
// function to play a single music file
//===================================
function PlayFile(fileName) {
    if (debugFlg == 1) {print ("%-I-INFO, PlayFile")};
	var 	isFolder = false;
	if (fileName=="" || fileName == null) { return };
	playListfileCount = 1;
	PlayIndex=1;
	playerState = "single";
	isAudioCD = false;
	IsPlaylist = false;
	/*
	if(fileName.length > 4) {
		var ext = fileName.substring(fileName.length - 3).toLowerCase();
		IsPlaylist = (ext == "m3u") || (ext == "wpl") || (ext == "wax");
		filePlayList = 0;
		currentFile = fileName;
	} else {
		IsPlaylist = false;
	}
	*/


       if(IsPlaylist) {
		WMPlayer.URL = fileName;
		sliderTimer.ticking = true;

                  print("1. WMPlayer.controls.play ");
                   WMPlayer.controls.play();

		PlayIndex = 0;
	} else {
		thePlayList = new Array(1);
		thePlayList[0] = new FileMedia(fileName);
                if (debugFlg == 1) {print ("Playmedia Call no. 2")};
                PlayMedia(0);
	}

    playButton.visible=false;
    pauseButton.visible=true;

}
//=====================
//End function
//=====================
 
//===================================
// function to open a folder and recursively read its contents into a playlist
//===================================
function ReadFolderRecursively(path) {
    if (debugFlg == 1) {print ("%-I-INFO, ReadFolderRecursively")};
    isFolder = true;
	chunkIndex = 0;
	isAudioCD = false;
	IsPlaylist = false;
// 	chosenFolder = path;
	var fs = null;

	mediapopupplaque.visible = true;
	sleep (350);
	if (preferences.recurseFoldersPref.value=="enabled") {
		// the getDirectoryContents when performed recursively can hang the widget in a loop until resources are used up
		// Instead the countDirContents function does that but when it reaches a limit of 10000 it aborts and generates an error.

		var interimFileCount = countDirContents(path);
		//print("interimFileCount prior to recursive search "+ interimFileCount);
		//print("fileCountLimit "+ fileCountLimit);	
		
		if (interimFileCount >= fileCountLimit ) {
			alert('In this folder and below there are more than "' + fileCountLimit + '" files the media player has to search through in order to build a playlist. This is too many. The widget will fail due to excessive memory usage. Select a sub-folder with less than "' + fileCountLimit + '" valid files or disable recursive search.');
			mediapopupplaque.visible = false;
			return;
		} else {
			fs = filesystem.getDirectoryContents(path, true);
		}
	} else {
		fs = filesystem.getDirectoryContents(path, false);
	}
	
	mediapopupplaque.visible = false;
	
	playListfileCount = fs.length;
	if (debugFlg == 1) {print("Filesystem recursive search file count " +playListfileCount)};

        tmfilePlayList = new Array(fs.length);
	dirList = new Array(fs.length);

	idxFile = 0;
	var idxFolder = 0;

	for(var i = 0; i < fs.length; i++) {
		if (! filesystem.isDirectory(path + "\\" + fs[i])) {
			if (validTypes.indexOf(xtn(fs[i])) >= 0 ) {
				IsSong = true;
			} else {
				IsSong = false;
			}
			if (IsSong) {
				tmfilePlayList[idxFile] = new FileMedia(path + "\\" + fs[i]);
                idxFile++;
			}else {
				// do nothing
                // print ("Found invalid types - "+ fs[i]);
            }
		} else {
			dirList[idxFolder] = new FileMedia(path + "\\" + fs[i]);
			idxFolder++;
		}
	}
	if (debugFlg == 1) {print ("Filesystem valid file count - adding "+ idxFile + " valid files to list.")};
	
	playListfileCount = idxFile;
	
	if (idxFile > 0) {
		thePlayList = new Array(idxFile);
		for(var i = 0; i < idxFile; i++) {
			thePlayList[i] = tmfilePlayList[i];
			IsPlaylist = true;
		}
                       if (debugFlg == 1) {print ("Playmedia Call no. 3")};
                       PlayMedia(0);
	} else {
               alert('In this folder "' + path + '" there are no files the media player can use. Please select the folder where your music resides.');
               openFolderToPlay();
    }

	checkShuffleState();


}
//=====================
//End function
//=====================

//=================================
// Function to count the folder contents folder by folder
//=================================
function countDirContents(path) {
	if (debugFlg == 1) {print ("%-I-INFO, countDirContents")};
	var totalFilesCount = 0;

	if (debugFlg == 1) {print ("recursively checking the contents of this folder - " + path)};

	// define the getFileList function
	filesystem.getFileList = function (path, limit) {
		var result = [];
		
		if (!filesystem.isDirectory(path)) {
			return result;
		}
		
		if (limit === undefined) {
			limit = 10000;    // default limit, if limit parameter omitted
		}

		function getFileList(path) {
			var paths;
			paths = filesystem.getDirectoryContents(path, false);
                        for(var i = 0; i < paths.length; i++)
                        {
				var fpath = paths[i];
				if (limit <= 0) {
					throw new Error("Limit Exceeded!");
				}

				//fpath = path + "/";
				if (filesystem.isDirectory(fpath)) {
					getFileList(fpath);
				} else {
					result.push(fpath);
					
					limit -= 1;             // counts files found
				}
			};
		}

		try {
			getFileList(path);
		} catch (e) {
			print(e);
		}
		return result;
	};

	
	var files = filesystem.getFileList(path, fileCountLimit);
	for(var i = 0; i < files.length; i++)
        {
		totalFilesCount  = totalFilesCount  + 1;
	};
	
	if (debugFlg == 1) {print("Interim manual file count prior to automatic recursive search "+ totalFilesCount)};
	return totalFilesCount;
}
//=================================
// end function
//=================================

//===================================
// function to read the data from an audio CD into the playlist
//===================================
function PlayAudioCD(cdDriveName, cdRomPlayList) {
	// this function is the CD equivalent of ReadFolderRecursively
        if (debugFlg == 1) {print ("%-I-INFO, PlayAudioCD")};
        isAudioCD = true;
	IsFolder = false;
	IsPlaylist = true;
        playerState = "AudioCD";
	oCDROM = CDROM.Item(cdDriveName);
	colPlaylist = oCDROM.Playlist;
	chunkIndex = 0;

	cdPlaylistTitles = new Array(cdRomPlayList.count);
	cdPlaylistArtists = new Array(cdRomPlayList.count);
        playListfileCount = cdRomPlayList.count;
        print("********************playListfileCount  "+ playListfileCount);
        if (playListfileCount != 0) {
           for(var i = 0; i < cdRomPlayList.count; i++) {
		if (!colPlaylist.Item(i)) {alert('CD drive is having a problem');};
		objSong = colPlaylist.Item(i);

		cdPlaylistTitles[i] = objSong.getItemInfo("title");
		cdPlaylistArtists[i] = objSong.getItemInfo("artist");

                print("cdPlaylistTitles[i]] "+cdPlaylistTitles[i]);

		thePlayList[i] = cdRomPlayList.Item(i);
		WMPlayer.URL = thePlayList[i].sourceURL;
		//print("thePlayList[i].sourceURL "+thePlayList[i].sourceURL);
                //print("thePlayList[i].sourceURL "+thePlayList[i].sourceURL);

		var artist = Trim(cdPlaylistArtists[i]);
		if (artist != "") artist = ": " + artist;

		trackName[i]= i + 1 + " " + Trim(cdPlaylistTitles[i]);
                print("trackName[i] "+trackName[i]);
                print("cdPlaylistTitles[i] "+cdPlaylistTitles[i]);
           }
        } else {
            alert('CD drive is not loaded');
            return;
	}
	//playListTitle.data  = "Audio CD Drive "+ CDROM.Item(cdRomNo).driveSpecifier;
	//print ("PlayAudioCD "+WMPlayer.URL);

	var artist = Trim(cdPlaylistArtists[i]);
	if (artist != "") artist = ": " + artist;

	if (preferences.shuffleStatePref.value=="enabled") {
		//randomPlay();
	}

	// provide the track information to the track data above the slider itself
	trackNoText.data = "track "+ WMPlayer.currentMedia.name.substring(0, 6);

	if (debugFlg == 1) {print ("trackNameText.data " + trackNameText.data)};
	
	//trackNameText.data is derived from chosenfolder used during updatePlayList function
	chosenFolder = CDROM.Item(cdRomNo).driveSpecifier + " " +  objSong.getItemInfo("AlbumID");
        if (debugFlg == 1) {print ("Playmedia Call no. 4")};

	// now it calls the function that actually plays the CD
	PlayMedia(0);
	//finally it updates the playlist
	updatePlayList();
}
//=====================
//End function
//=====================

//===================================
// function to play any media CD or playlist, called by nextButton, prevButton &c
//===================================
function PlayMedia(i) {
  if (debugFlg == 1) {print ("%-I-INFO, PlayMedia")};
  if (playListfileCount>0) {
        PlayIndex = i;
        if (debugFlg == 1) {
			print("playListfileCount "+playListfileCount);
			print("PlayIndex "+PlayIndex);
			print("thePlayList[i].sourceURL "+thePlayList[i].sourceURL);
        }

	WMPlayer.URL = thePlayList[i].sourceURL;

	// set the track display data

        if (isAudioCD) {
	              //print ("Audio CD " +WMPlayer.currentMedia.duration);
		      var artist = Trim(cdPlaylistArtists[i]);
		      if (artist != "") artist = ": " + artist;
        	      trackNameText.data = Trim(cdPlaylistTitles[i]) + artist;
                      trackNoText.data = "track "+ WMPlayer.currentMedia.name.substring(0, 6);
	} else {
                      if (preferences.titlePref.value == "filename only" ) {
                        trackNameText.data = "   " + getFileOnly(WMPlayer.URL);
                      } else {
                        trackNameText.data = "   " + WMPlayer.URL;
                      }
                      //if the random button is pressed then
                      if (preferences.shuffleStatePref.value == "enabled") {
		        trackNoText.visible= false;
                      } else {
			trackNoText.data = "track "+ eval(PlayIndex + 1);
			trackNoText.visible= true;
		      }
	}
	if (debugFlg == 1) {
			print ("trackNameText.data " + trackNameText.data);
			print ("trackNoText.data " + trackNoText.data);
	}

        if (playOverride === false) {
           positionTimer.ticking=true;
           sliderTimer.ticking = true;
           WMPlayer.controls.play();
           playButton.visible=false;
           pauseButton.visible=true;  //ywe
        }
        // this next call is absolutely necessary, removes the styling at the point the track is selected and playing
	scrollPlayList();
  }
  if (debugFlg == 1) {print("WMPlayer.URL "+ WMPlayer.URL)};

}
//=====================
//End function
//=====================

//===================================
// function to play currently selected track
//===================================
function playTrack() {
  if (debugFlg == 1) {print ("%-I-INFO, playTrack")};
  trackNameText.scrolling="left";
  if (playListfileCount >= 1) {
        playButton.visible = false;
        pauseButton.visible = true;                                        
        if (WMPlayer.controls.currentPosition == WMPlayer.currentMedia.duration) {
                WMPlayer.controls.currentPosition = 0;
        }
        //print("3. WMPlayer.controls.play ");
        WMPlayer.controls.play();
        playOverride = false;
        positionTimer.ticking=true;
        sliderTimer.ticking = true;
	    buildVitality(currIcon, parseInt(percentTextShadow.data, 10), WMPlayer.settings.mute); // build the dock vitality
		if (debugFlg == 1) {print("player.currentMedia.duration "+WMPlayer.currentMedia.duration)};
  }
}
//=====================
//End function
//=====================

//===================================
// function to add a single track for immediate playing
//===================================
function addSingleTrack() {
    if (debugFlg == 1) {print ("%-I-INFO, addSingleTrack")};
	if (preferences.soundpref.value === "enabled") {
	   play(winding, false);
	}
	playlistFrame.visible= false;

        fileName = chooseFile(validTypes);
        //print("fileName "+fileName);
        PlayFile(fileName);
        if (fileName != null) {
          chosenFolder = "";
        }
}
//=====================
//End function
//=====================

//===================================
// function to tell the WMP to pause
//===================================
function pauseTrack() {
  if (debugFlg == 1) {print ("%-I-INFO, pauseTrack")};
  if (playListfileCount>0) {
        trackNameText.scrolling="off";
	WMPlayer.controls.pause();
	//stop the timers, no point in them running
	sliderTimer.ticking=false;
	positionTimer.ticking=false;
  }
}
//=====================
//End function
//=====================

//===================================
// function to select the previous track
//===================================
function previousTrack() {
    if (debugFlg == 1) {print ("%-I-INFO, previousTrack")};
        positionTimer.ticking = false;
        playOverride = false;
        //print("playListfileCount "+playListfileCount);
        //print("PlayIndex "+PlayIndex);
        //print("playerState "+playerState);
        trackNameText.scrolling="left";
        if (!WMPlayer.URL) {
            return;
        } else {
           if (playerState == "single")  {
              //print("4. WMPlayer.controls.play ");
              WMPlayer.controls.play();
              positionTimer.ticking=true;
              sliderTimer.ticking = true;

              return;
            }
    	    if (PlayIndex >0 ) {
                    PlayIndex--;
            } else {
                    PlayIndex = playListfileCount - 1;
            }
            if (debugFlg == 1) {print ("Playmedia Call no. 5")};
            PlayMedia(PlayIndex);
         }
        //print("WMPlayer.URL"+ WMPlayer.URL);
        positionTimer.ticking = true;
}
//=====================
//End function
//=====================

//===================================
// function to select the next track
//===================================
function nextTrack() {
    if (debugFlg == 1) {print ("%-I-INFO, nextTrack")};
        positionTimer.ticking = false;
        playOverride = false;
        trackNameText.scrolling="left";
        if (!WMPlayer.URL) {
            return;
        } else {
            if (playerState == "single")  {
                //print("5. WMPlayer.controls.play ");
                WMPlayer.controls.play();
                positionTimer.ticking=true;
                return;
            }
            if (PlayIndex+1 < playListfileCount ) {
                    PlayIndex++;
                    trackIndex++;
					if (debugFlg == 1) {print("trackIndex "+trackIndex)};

                    if (trackIndex == 12) {
                      trackIndex = 1;
                      chunkIndex = chunkIndex + 1;
					  if (debugFlg == 1) {print("chunkIndex "+chunkIndex)};
					  if (debugFlg == 1) {print("trackIndex "+trackIndex)};
					  
					  updatePlayList();
                    };
            } else {
                    PlayIndex = 0;
            }
            if (debugFlg == 1) {print ("Playmedia Call no. 6")};
            PlayMedia(PlayIndex);
            positionTimer.ticking=true;
            positionSliderperc = 0;
        }
        //print("WMPlayer.URL"+ WMPlayer.URL);
        positionTimer.ticking = true;
}
//=====================
//End function
//=====================

//===================================
// function to emulate LTrim
//===================================
function LTrim(str) {
	var whitespace = new String(" \t\n\r");
	var s = new String(str);
	if (whitespace.indexOf(s.charAt(0)) != -1) {
		var j=0, i = s.length;
		while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
			j++;
			s = s.substring(j, i);
	}
	return s;
}
//=====================
//End function
//=====================

//===================================
// function to emulate RTrim
//===================================
function RTrim(str) {
	var whitespace = new String(" \t\n\r");
	var s = new String(str);
	if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
		var i = s.length - 1;
		while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
			i--;
			s = s.substring(0, i+1);
	}
	return s;
}
//=====================
//End function
//=====================

//===================================
// function to trim a string both ends
//===================================
function Trim(str) {
	return RTrim(LTrim(str));
}
//=====================
//End function
//=====================


//===================================
// function to get the filename only
//===================================
function getFileOnly(str) {
         file_extension = str.split('.').pop();
         return str.replace(/^.*[\\\/]/, '')

}
//=====================
//End function
//=====================

//===================================
// function to save the last used music folder path
//===================================
 function saveFolder(path){
    if (debugFlg == 1) {print ("%-I-INFO, saveFolder")};
	if (path == "") {
	      return;
	}
        if (preferences.musicFolderPref.value != "") {
                if (preferences.musicFolderPref2.value != "") {
                        if (preferences.musicFolderPref3.value != "") {
                              if (preferences.musicFolderPref4.value != "") {
                                      preferences.musicFolderPref5.value = preferences.musicFolderPref4.value;
                              }
                              preferences.musicFolderPref4.value = preferences.musicFolderPref3.value;
                        }
                	preferences.musicFolderPref3.value = preferences.musicFolderPref2.value;
                }
        	preferences.musicFolderPref2.value = preferences.musicFolderPref.value;
        }
       	preferences.musicFolderPref.value = path;
}
//=====================
//End function
//=====================

//===================================
// function to check the music folder path
//===================================
function checkPath(){
    if (debugFlg == 1) {print ("%-I-INFO, checkPath")};
	//preferences.musicFolderPref.value = "D:\\Music";
		if (debugFlg == 1) {print("preferences.musicFolderPref.value "+preferences.musicFolderPref.value)};
        if (preferences.musicFolderPref.value == "") {
	      preferences.musicFolderPref.value = "C:\\Users\\Public\\Music";
	}
        //now restrict the user from selecting the root folders
        restrictRootFolder();
		if (debugFlg == 1) {print ("preferences.musicFolderPref.value "+ preferences.musicFolderPref.value)};
        //preferences.musicFolderPref.value = "D:\\Music";
	path = preferences.musicFolderPref.value ;
}
//=====================
//End function
//=====================

//===================================
// function to shuffle the play list or file list
//===================================
function toggleRandomPlay() {
   if (debugFlg == 1) {print ("%-I-INFO, toggleRandomPlay")};
 
   if (preferences.shuffleStatePref.value == "disabled") { 
	   preferences.shuffleStatePref.value = "enabled";
	   //print ("1. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ preferences.shuffleStatePref.value " + preferences.shuffleStatePref.value);	

		pipesRight.src="Resources/pipesRightClicked.png";
		if (debugFlg == 1) {print ("toggling the random state to " + preferences.shuffleStatePref.value)};
                if (preferences.tooltipPref.value == "enabled") {
                   pipesRight.tooltip = "pulled out - shuffle is now enabled";
                } else {
                   pipesRight.tooltip = "";
                }
		randomPlay();
   } else { //preferences.shuffleStatePref.value = "enabled"
	    //print ("2. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ preferences.shuffleStatePref.value " + preferences.shuffleStatePref.value);
                pipesRight.src="Resources/pipesRight.png";
		preferences.shuffleStatePref.value = "disabled"
		if (debugFlg == 1) {print ("toggling the random state to " + preferences.shuffleStatePref.value)};
                if (preferences.tooltipPref.value == "enabled") {
		   pipesRight.tooltip = "pushed in - shuffle is now disabled";
                } else {
                   pipesRight.tooltip = "";
                }

		if (!isAudioCD) {
			ReadFolderRecursively(path);  //only re-read the default folder when not a CD
		} else {
                        if (CDROMcount != 0 ) {
                            PlayAudioCD( 0 , CDROM.Item(cdRomNo).Playlist);
                        }
		}
		
		updatePlayList();
   }
   if (preferences.soundpref.value === "enabled") {
      	play(lock, false);
   }

}
//=====================
//End function
//=====================

//===================================
// function to shuffle an existing play list or file list
//===================================
function randomPlay() {
   if (debugFlg == 1) {print ("%-I-INFO, randomPlay")};
   print("playListfileCount  "+playListfileCount );   
	if (playerState == "folder"  || playerState == "AudioCD")  {
		var i = playListfileCount ;
		if (i == 0) return false;	
		while (--i) {
				var j = Math.floor( Math.random() * (i + 1));
				var tempi = thePlayList[i];
				var tempj = thePlayList[j];
				thePlayList[i] = tempj;
				thePlayList[j] = tempi;
				if (isAudioCD) {
					var objSongi = cdPlaylistTitles[i];
					var objSongj = cdPlaylistTitles[j];
					cdPlaylistTitles[i] = objSongj;
					cdPlaylistTitles[j] = objSongi;
				}
			}
                        if (debugFlg == 1) {print ("Playmedia Call no. 7")};
                        PlayMedia(0);
			playerState = "folder"; //this is to ensure that shuffle mode is respected
			//print ("1^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ path " + path);
			if (debugFlg == 1) {print ("Randomising done " )};

			updatePlayList();
		//print ("2 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^path " + path);
	}   
}
//=====================
//End function
//=====================

//===================================
// function to capture a mousewheel event
//===================================
pipes.onMouseWheel = function (event) {
     if (event.ctrlKey) {
        capMouseWheel(event);    //this event is not captured in the Xwidget version
     } else {
        sliderSetOnMouseWheel();
     }
};
//=====================
//End function
//=====================


//===================================
// function to capture a mousewheel event
//===================================
playlistFrame.onMouseWheel = function (event) {
     if (event.ctrlKey) {
        capMouseWheel(event);    //this event is not captured in the Xwidget version
     } else {
        playlistFrameOnMouseWheel(event)
     }
};
//=====================
//End function
//=====================


//===================================
// function to resize using mousewheel + CTRL key as per Firefox
//===================================
function capMouseWheel(event) {
	var size = Number(preferences.maxWidthPref.value),
		maxLength = Number(preferences.maxWidthPref.maxLength),
		minLength = Number(preferences.maxWidthPref.minLength),
		ticks = Number(preferences.maxWidthPref.ticks),
		step = Math.round((maxLength - minLength) / (ticks - 1));


		if (event.scrollDelta > 0) {
			if (preferences.MouseWheelPref.value === "up") {
				size -= step;
				if (size < minLength) {
					size = minLength;
				}
			} else {
				size += step;
				if (size > maxLength) {
					size = maxLength;
				}
			}
		} else if (event.scrollDelta < 0) {
			if (preferences.MouseWheelPref.value === "up") {
				size += step;
				if (size > maxLength) {
					size = maxLength;
				}
			} else {
				size -= step;
				if (size < minLength) {
					size = minLength;
				}
			}
		}
		preferences.maxWidthPref.value = String(size);
                //screenwrite("using mousewheel");
                resize();

  }
//=====================
//End function
//=====================


//===================================
// functions to capture onDragDrops
//===================================
playListText11.onDragDrop = function () {
  dropPosition = 11;
  catchFileDrop();
}

playListText10.onDragDrop = function () {
  dropPosition = 10;
  catchFileDrop();
}

playListText9.onDragDrop = function () {
  dropPosition = 9;
  catchFileDrop();
}

playListText8.onDragDrop = function () {
  dropPosition = 8;
  catchFileDrop();
}

playListText7.onDragDrop = function () {
  dropPosition = 7;
  catchFileDrop();
}

playListText6.onDragDrop = function () {
  dropPosition = 6;
  catchFileDrop();
}

playListText5.onDragDrop = function () {
  dropPosition = 5;
  catchFileDrop();
}

playListText4.onDragDrop = function () {
  dropPosition = 4;
  catchFileDrop();
}

playListText3.onDragDrop = function () {
  dropPosition = 3;
  catchFileDrop();
}

playListText2.onDragDrop = function () {
  dropPosition = 2;
  catchFileDrop();
}

playListText1.onDragDrop = function () {
  dropPosition = 1;
  catchFileDrop();
}

playListText0.onDragDrop = function () {
  dropPosition = 0;
  catchFileDrop();
}
//=====================
//End functions
//=====================

//===========================================
// function to accept a file on drag and drop
//===========================================
playlistFrame.onDragDrop = function () {
  //catchFileDrop();
};
//=====================
//End function
//=====================

//===========================================
// function to accept a file on drag and drop
//===========================================
pipes.onDragDrop = function () {
  //catchFileDrop();
};
//=====================
//End function
//=====================

//===========================================
// function to accept a file on drag and drop
//===========================================
function catchFileDrop() {
    if (debugFlg == 1) {print ("%-I-INFO, pipes.onDragDrop")};

    var n = system.event.data.length,
    	dropData = [],
    	i,
    	dropType,
    	validFound = 0,
    	files,
    	processFiles,
        f,
        j,
        directoryFiles,
        directoryFile,
        answer,
        path,
        xtype,
        isFolder;

    if (debugFlg == 1) {print ("Reading dropped items - "+ n)};
    //only read less than 10,000 individual files
    if (n <= fileCountLimit ) {
           for (i = 0; i < n; i += 1) { dropData[i] = system.event.data[i]; }
    } else {
	  alert('In this drag/drop operation there are more than "' + fileCountLimit + '" files. Please select a much smaller amount!');
	  return;
    }

    dropType = dropData[0];

    f = dropData[1];
    chosenFolder = f;
    path = chosenFolder;
    if (filesystem.isDirectory(f)) {
        dropType = "folder";
        isFolder=true;
    } else {
        dropType = "filenames";
        isFolder=false;
    }

    files = [];
    processFiles = true;
    print("xxxxxxxxxxxxxdropType "+ dropType);
    if (dropType == "folder") {

    //print("chosenFolder"+f);
    //print("chosenFolder"+chosenFolder);
            // If a folder is dropped, its contents will be added to the list
            if (isFolder === true) {
                print("isFolder "+ isFolder);
                             //add the files to the playlist
                ReadFolderRecursively(f);
                saveFolder(f);
                updatePlayList();
           }
   }

    if (dropType === "filenames") {
              // dropped file or files
              dropType = dropData[0];
	     //print("drop data length "+ dropData.length);
              n = dropData.length;

                   // add multiple files to the playlist
                   var tmpfilePlayList = new Array(n);
                   idxFile = 0;
                   IsPlaylist =true;
		   for (i = 1; i < n; i += 1) {   // loop starts from one as the zero location contains type
                           path = dropData[i];
                           if (validTypes.indexOf(xtn(path)) >= 0 ) {
                                validFound=1;
                                //add to the temporary play list
    				tmpfilePlayList[idxFile]=new FileMedia(dropData[i]);
				if (debugFlg == 1) {print("Added "+dropData[i]+" to the play list")};
				idxFile = idxFile + 1;
                            }
                    }
                    if (validFound==1) {
			if (createNewList == 1) {
                            //
    			    thePlayList = new Array(idxFile);
    			    //add to the final play list
    			    for(var i = 0; i < idxFile; i++) {
    			        thePlayList[i] = tmpfilePlayList[i];
    			        //print("*********** thePlayList[i] " +thePlayList[i].sourceURL);
    			    }
    			    //print("*********** playListfileCount " +playListfileCount);
    			    playListfileCount = idxFile;
                            if (debugFlg == 1) {print ("Playmedia Call no. 8")};
    			    PlayMedia(0); // play from the first track in the WMP playlist
    			    updatePlayList();
			}
			// drag and drop on the playlist adds to existing list rather than replace altogether
			if (createNewList == 0) {
                            // create a new playlist the current size but with the additional elements added - idxfile + playlist.length
                            biggerPlayListSize = idxFile + thePlayList.length ;
    			    var conjoinedPlayList = new Array(biggerPlayListSize);

                            // copy all the old elements to the new playlist up to the point where the drop has occurred - dropPosition
    			    for(var i = 0; i < dropPosition; i++) {   // loop from 0 to the drop point
    			        conjoinedPlayList[i] = thePlayList[i];
    			        //print("*********** 1 conjoinedPlayList[" + i + "] " + conjoinedPlayList[i].sourceURL);
                            }


    			    //if (n == 1) {  // single file
                            //        conjoinedPlayList[dropPosition] = tmpfilePlayList[j];
                            //} else {

    			    // drop the new elements at this point - idxfile is the count of the valid items
    			    j = 0;
    			    for(var i = dropPosition; i < (dropPosition+idxFile); i++) {
    			        conjoinedPlayList[i] = tmpfilePlayList[j];
    			        j=j+1;
    			        //print("*********** 2 conjoinedPlayList[" + i + "] " + conjoinedPlayList[i].sourceURL);
    			    }


    			    // copy the rest of the old elements to the new playlist after the new items have been dropped

                            j = dropPosition;
    			    for(var i = dropPosition + idxFile; i <= biggerPlayListSize; i++) {
    			        if (thePlayList[i]!= null) {
                                       conjoinedPlayList[i] = thePlayList[j];
                                       //conjoinedPlayList[i] = "";
                                       j=j+1;
                                       //print("*********** 3 conjoinedPlayList[" + i + "] " +conjoinedPlayList[i].sourceURL);
                                    };
    			    }

    			    //print("*********** playListfileCount " +playListfileCount);
    			    playListfileCount = biggerPlayListSize;

    			    // these two array transfer commands do not work as expected

                            // this copied the array but only in the context of this subroutine as if it was a local variable declaration
                            // thePlayList.push.apply(thePlayList, conjoinedPlayList);
                            // thePlayList = Array.from(conjoinedPlayList);    // failed completely

                            //add to the final play list
    			    for(var i = 0 ; i <= biggerPlayListSize; i++) {
    			        if (conjoinedPlayList[i]!= null) {
                                       thePlayList[i] = conjoinedPlayList[i];
                                       //print("*********** 4 thePlayList[i] " +thePlayList[i].sourceURL);
                                };
    			    }

                            if (debugFlg == 1) {print ("Playmedia Call no. 8")};
    			    PlayMedia(0); // play from the first track in the WMP playlist
    			    updatePlayList();
			}
                } else {
			alert('That selection does not contain a music file that the media player can use.');
		}
   }
};
//=====================
//End function
//=====================

//===================================
// set the widget lock status if pinned
//===================================
function checkLocked() {
    if (debugFlg == 1) {print ("%-I-INFO, checkLocked")};
    if (preferences.widgetLockPref.value === "1") {
		mainWindow.locked = true;
                log ( "Setting the locking pin ",lockArea.vOffset);
		lockArea.visible=false;
		lockAreaLocked.visible=true;
      	        if (preferences.soundpref.value === "enabled") {
      		   play(lock, false);
      	        }
    }
};
//=====================
//End function
//=====================

//===================================
// set the saved shuffle status
//===================================
function checkShuffleState() {
    if (debugFlg == 1) {print ("%-I-INFO, checkShuffleState")};
       if (preferences.shuffleStatePref.value=="enabled") {
	        //print ("1. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ preferences.shuffleStatePref.value " + preferences.shuffleStatePref.value);
                pipesRight.src="Resources/pipesRightClicked.png";
		if (preferences.tooltipPref.value == "enabled") {
                   pipesRight.tooltip = "pulled out - shuffle is now enabled";
                } else {
                   pipesRight.tooltip = "";
                }
               	randomPlay();
       } else {
		if (preferences.tooltipPref.value == "enabled") {
		   pipesRight.tooltip = "pushed in - shuffle is now disabled";
                } else {
                   pipesRight.tooltip = "";
                }
       }
};
//=====================
//End function
//=====================

//===================================
// set the autoplay state read the default folder
//===================================
function checkAutoPlayState() {
          playerState = "folder"; //this is to ensure that shuffle mode is respected
          if (startupFlg == 1 && preferences.autoPlayStatePref.value == "disabled") {
             playOverride = true;
             positionTimer.ticking = false;
          }
          path = preferences.musicFolderPref.value;
          chosenFolder = preferences.musicFolderPref.value;
       	  ReadFolderRecursively(preferences.musicFolderPref.value);

};
//=====================
//End function
//=====================

//===========================================
// this function opens Google to search using the track name
//===========================================
trackNameText.onMultiClick = function () {
	if (debugFlg == 1) {print ("%-I-INFO, trackNameText.onMultiClick")};
	var searchTrack = getFileOnly(trackNameText.data);
	var answer = alert(" This opens a browser window and searches the internet for this track name: " +  String.fromCharCode(13) + searchTrack + String.fromCharCode(13) + "                              Do you wish to proceed?                         ", "Open Browser Window", "No Thanks");
	if (answer === 1) {
		openURL("https://www.google.co.uk/?gws_rd=ssl#q="+searchTrack);
	}
}

//=====================
//End function
//=====================

//===========================================
// this function serves to cause the icon to change on a mouseover only, the multiclick event does not change the mouse over icon
//===========================================
trackNameText.onMouseDown = function () {
	if (debugFlg == 1) {print ("%-I-INFO, trackNameText.onMouseDown")};
}

//=====================
//End function
//=====================

//===================================
// function to update the play list
//===================================
function updatePlayList() {
	if (debugFlg == 1) {print ("%-I-INFO, updatePlayList")};
	wipePlayList();
	clearPlayList();
	readPlayList();
	removePlayListScrolling()
	removePlayListStyling();
	log("chosenFolder "+chosenFolder);
	playListTitle.data =  chosenFolder;
	if (chosenFolder == "") {
		playListTitle.data =  preferences.musicFolderPref.value; // just in case the playlist is absent due to invalid or missing files
	}
	log("IsPlaylist "+IsPlaylist);	
	if (IsPlaylist != false || playListfileCount==1) {
		showPlayList();
	}
	setPlayListTooltip();
	buttonOpacity();
	highlightPlayingTrack();
}
//=====================
//End function
//=====================

//===================================
// function to read the play list
//===================================
function clearPlayList() {
    if (debugFlg == 1) {print ("%-I-INFO, clearPlayList")};
    trackName = new Array(idxFile)      ;
    fullTrackName = new Array(idxFile)  ;

	playListText0.data = "";
	playListText1.data =  "";
	playListText2.data =  "";
	playListText3.data =  "";
	playListText4.data =  "";
	playListText5.data =  "";
	playListText6.data =  "";
	playListText7.data =  "";
	playListText8.data =  "";
	playListText9.data =  "";
	playListText10.data =  "";
	playListText11.data =  "";

}
//=====================
//End function
//=====================

//===================================
// read the play list
//===================================
function readPlayList() {
	if (debugFlg == 1) {print ("%-I-INFO, readPlayList")};

	trackNoText.data = "track "+ WMPlayer.currentMedia.name.substring(0, 6);

	if (playListfileCount==1) { //single file

		trackName[0]= getFileOnly(thePlayList[0].sourceURL);
		fullTrackName[0]= convertPathToPlatform(thePlayList[0].sourceURL);

	} else { //multiple files
		for(var i = 0; i <= chunkSize; i++) {
			var j = i + (12 * chunkIndex);
			trackNumber[j]= j;
			//print (">>>>>>>>>>>>>>>>>>>>>> j " + j);
			//print ("playListfileCount " + playListfileCount);

			if (j <= playListfileCount-1) {
				if (isAudioCD) {
					trackName[j]= j + 1 + " " + Trim(cdPlaylistTitles[j]);
				} else {
					// this is the track as displayed in the track list
					trackName[j]= getFileOnly(thePlayList[j].sourceURL);
					//print ("&&&&&&&&&&&&&&&&& fullTrackName[j] " + fullTrackName[j]);
					//print ("trackName[j] " + trackName[j]);

				}
				// this is the full track path converted to native format
				fullTrackName[j]= convertPathToPlatform(thePlayList[j].sourceURL);

			}
		}
	}
}
//=====================
//End function
//=====================

//===================================
// this routine is here for cleanliness during debugging, it wipes the play list
//===================================
function wipePlayList() {
	if (debugFlg == 1) {print ("%-I-INFO, wipePlayList")};

	for(var i = 0; i <= chunkSize; i++) {
		var j = i + (12 * chunkIndex);
		trackNumber[j]= j;
		//print (">>>>>>>>>>>>>>>>>>>>>> j " + j);
		if (j <= playListfileCount-1) {
				// this is the track as displayed in the track list
			trackName[j]= "";
			// this is the full track path converted to native format
			fullTrackName[j]= "";
		}
	}
}
//=====================
//End function
//=====================

//===================================
// display a chunk of the tracks
//===================================
function showPlayList() {
    if (debugFlg == 1) {print ("%-I-INFO, showPlayList")};

		playListPage.data = "  Page no. " + parseInt(chunkIndex + 1) ;

		if (playListfileCount==1) { //single file
			playListText0.data = trackName[0];
		} else {
			if (debugFlg == 1) {print("chunkIndex "+chunkIndex)};
			if (trackName[0+ (12 * chunkIndex)] != null ) {playListText0.data = trackName[0+ (12 * chunkIndex)].toLowerCase()};
			if (trackName[1+ (12 * chunkIndex)] != null ) {playListText1.data =  trackName[1+ (12 * chunkIndex)].toLowerCase()};
			if (trackName[2+ (12 * chunkIndex)] != null ) {playListText2.data =  trackName[2+ (12 * chunkIndex)].toLowerCase()};
			if (trackName[3+ (12 * chunkIndex)] != null ) {playListText3.data =  trackName[3+ (12 * chunkIndex)].toLowerCase()};
			if (trackName[4+ (12 * chunkIndex)] != null ) {playListText4.data =  trackName[4+ (12 * chunkIndex)].toLowerCase()};
			if (trackName[5+ (12 * chunkIndex)] != null ) {playListText5.data =  trackName[5+ (12 * chunkIndex)].toLowerCase()};
			if (trackName[6+ (12 * chunkIndex)] != null ) {playListText6.data =  trackName[6+ (12 * chunkIndex)].toLowerCase()};
			if (trackName[7+ (12 * chunkIndex)] != null ) {playListText7.data =  trackName[7+ (12 * chunkIndex)].toLowerCase()};
			if (trackName[8+ (12 * chunkIndex)] != null ) {playListText8.data =  trackName[8+ (12 * chunkIndex)].toLowerCase()};
			if (trackName[9+ (12 * chunkIndex)] != null ) {playListText9.data =  trackName[9+ (12 * chunkIndex)].toLowerCase()};
			if (trackName[10+ (12 * chunkIndex)] != null ) {playListText10.data =  trackName[10+ (12 * chunkIndex)].toLowerCase()};
			if (trackName[11+ (12 * chunkIndex)] != null ) {playListText11.data =  trackName[11+ (12 * chunkIndex)].toLowerCase()};
		}
}
//=====================
//End function
//=====================

//===================================
// set the play list tooltips
//===================================
function setPlayListTooltip() {
    if (debugFlg == 1) {print ("%-I-INFO, setPlayListTooltip")};
	if (isAudioCD) {
	   if (preferences.tooltipPref.value == "enabled") {
		playListTitle.tooltip =  "CD drive : "+playListTitle.data;
		playListText0.tooltip =  "CD track : "+trackName[0+ (12 * chunkIndex)];
		playListText1.tooltip =  "CD track : "+trackName[1+ (12 * chunkIndex)];
		playListText2.tooltip =  "CD track : "+trackName[2+ (12 * chunkIndex)];
		playListText3.tooltip =  "CD track : "+trackName[3+ (12 * chunkIndex)];
		playListText4.tooltip =  "CD track : "+trackName[4+ (12 * chunkIndex)];
		playListText5.tooltip =  "CD track : "+trackName[5+ (12 * chunkIndex)];
		playListText6.tooltip =  "CD track : "+trackName[6+ (12 * chunkIndex)];
		playListText7.tooltip =  "CD track : "+trackName[7+ (12 * chunkIndex)];
		playListText8.tooltip =  "CD track : "+trackName[8+ (12 * chunkIndex)];
		playListText9.tooltip =  "CD track : "+trackName[9+ (12 * chunkIndex)];
		playListText10.tooltip =  "CD track : "+trackName[10+ (12 * chunkIndex)];
		playListText11.tooltip =  "CD track : "+trackName[11+ (12 * chunkIndex)];
	    } else {
                clearPlayListHints();
	    }
	} else {
		if (playListfileCount==1) { //single file
			print (">>>>>>>>>>>>>>>>>>>>>> playListfileCount " + playListfileCount);
			print ("trackName[0] " + trackName[0]);
	                if (preferences.tooltipPref.value == "enabled") {
			   playListText0.tooltip =  fullTrackName[0];
        	        } else {
			   playListText0.tooltip =  "";
                        }
		} else {
	            if (preferences.tooltipPref.value == "enabled") {
			playListTitle.tooltip =  "Double click here to open selected folder";
			playListText0.tooltip =  fullTrackName[0+ (12 * chunkIndex)];
			playListText1.tooltip =  fullTrackName[1+ (12 * chunkIndex)];
			playListText2.tooltip =  fullTrackName[2+ (12 * chunkIndex)];
			playListText3.tooltip =  fullTrackName[3+ (12 * chunkIndex)];
			playListText4.tooltip =  fullTrackName[4+ (12 * chunkIndex)];
			playListText5.tooltip =  fullTrackName[5+ (12 * chunkIndex)];
			playListText6.tooltip =  fullTrackName[6+ (12 * chunkIndex)];
			playListText7.tooltip =  fullTrackName[7+ (12 * chunkIndex)];
			playListText8.tooltip =  fullTrackName[8+ (12 * chunkIndex)];
			playListText9.tooltip =  fullTrackName[9+ (12 * chunkIndex)];
			playListText10.tooltip =  fullTrackName[10+ (12 * chunkIndex)];
			playListText11.tooltip =  fullTrackName[11+ (12 * chunkIndex)];
        	    } else {
                        clearPlayListHints();
        	    }
                }
	}
}
//=====================
//End function
//=====================

//=====================
// functions to add hover over effects to the items in the playlist
//=====================
playListTitle.OnMouseEnter= function () {
   playListTitle.scrolling = "left";
}
//increase the font by one point, the extra 0.49 is added to cater for the scaling flattening the font size slightly
playListText0.OnMouseEnter= function () {
        playListText0.style.fontSize = (parseInt(fontDefault) + 1.49)  * Scale + "px";
        //deleteButton0.opacity=255;

}
playListText1.OnMouseEnter= function () {
        playListText1.style.fontSize = (parseInt(fontDefault) + 1.49) * Scale + "px";
        //deleteButton1.opacity=255;
}
playListText2.OnMouseEnter= function () {
        playListText2.style.fontSize = (parseInt(fontDefault) + 1.49)  * Scale + "px";
        //deleteButton2.opacity=255;
}
playListText3.OnMouseEnter= function () {
        playListText3.style.fontSize = (parseInt(fontDefault) + 1.49)  * Scale + "px";
        //deleteButton3.opacity=255;
}
playListText4.OnMouseEnter= function () {
        playListText4.style.fontSize = (parseInt(fontDefault) + 1.49)  * Scale + "px";
        //deleteButton4.opacity=255;
}
playListText5.OnMouseEnter= function () {
        playListText5.style.fontSize = (parseInt(fontDefault) + 1.49)  * Scale + "px";
        //deleteButton5.opacity=255;
}
playListText6.OnMouseEnter= function () {
        playListText6.style.fontSize = (parseInt(fontDefault) + 1.49)  * Scale + "px";
        //deleteButton6.opacity=255;
}
playListText7.OnMouseEnter= function () {
        playListText7.style.fontSize = (parseInt(fontDefault) + 1.49)  * Scale + "px";
        //deleteButton7.opacity=255;
}
playListText8.OnMouseEnter= function () {
        playListText8.style.fontSize = (parseInt(fontDefault) + 1.49)  * Scale + "px";
        //deleteButton8.opacity=255;
}
playListText9.OnMouseEnter= function () {
        playListText9.style.fontSize = (parseInt(fontDefault) + 1.49)  * Scale + "px";
        //deleteButton9.opacity=255;
}
playListText10.OnMouseEnter= function () {
        playListText10.style.fontSize = (parseInt(fontDefault) + 1.49)  * Scale + "px";
        //deleteButton10.opacity=255;
}
playListText11.OnMouseEnter= function () {
        playListText11.style.fontSize = (parseInt(fontDefault) + 1.49)  * Scale + "px";
        //deleteButton11.opacity=255;
}
//=====================
//End mouse enter functions
//=====================

//===========================================
// this function provides the mouse over icon change.
//===========================================
playListTitle.onClick = function () {
	// do not remove this empty function it has a purpose..
}
//=====================
//End function
//=====================

//===========================================
// this function opens explorer to view the folder
//===========================================
playListTitle.onMultiClick = function () {
	if (debugFlg == 1) {print ("%-I-INFO, trackNameText.onMultiClick")};
	if (isAudioCD == false) {
                if (preferences.tooltipPref.value == "enabled") {
			playListTitle.tooltip =  playListTitle.data;
	        } else {
                        playListText0.tooltip =  "";
                }

		var targetFullPath = convertPathToPlatform(playListTitle.data)+ "/";
		if (filesystem.itemExists(targetFullPath) )   {
			//dosCommand = "Explorer.exe /e, /select,E:\\Documents and Settings\\Dean Beedell\\My Documents\\My Widgets\\mars 2.widget";
			dosCommand = "Explorer.exe /e, /select," + targetFullPath;
			filesystem.reveal(targetFullPath);
		}            
	}
}
//=====================
//End function
//=====================

//=====================
// functions to show the track title back into normal state
//=====================
playListTitle.onMouseExit= function () {
   playListTitle.scrolling = "off";
}
playListText0.onMouseExit= function () {
        playListText0.style.fontSize = (fontDefault)  * Scale + "px";
}
playListText1.onMouseExit= function () {
        playListText1.style.fontSize = (fontDefault)  * Scale + "px";
}
playListText2.onMouseExit= function () {
        playListText2.style.fontSize = (fontDefault)  * Scale + "px";
}
playListText3.onMouseExit= function () {
        playListText3.style.fontSize = (fontDefault)  * Scale + "px";
}
playListText4.onMouseExit= function () {
        playListText4.style.fontSize = (fontDefault)  * Scale + "px";
}
playListText5.onMouseExit= function () {
        playListText5.style.fontSize = (fontDefault)  * Scale + "px";
}
playListText6.onMouseExit= function () {
        playListText6.style.fontSize = (fontDefault)  * Scale + "px";
}
playListText7.onMouseExit= function () {
        playListText7.style.fontSize = (fontDefault)  * Scale + "px";
}
playListText8.onMouseExit= function () {
        playListText8.style.fontSize = (fontDefault)  * Scale + "px";
}
playListText9.onMouseExit= function () {
        playListText9.style.fontSize = (fontDefault)  * Scale + "px";
}
playListText10.onMouseExit= function () {
        playListText10.style.fontSize = (fontDefault)  * Scale + "px";
}
playListText11.onMouseExit= function () {
        playListText11.style.fontSize = (fontDefault)  * Scale + "px";
}
//=====================
//End mouse exit functions
//=====================

//=====================
// functions to set the background on the single-clicked tracks 
//=====================
playListText0.onMouseDown= function () {
        removePlayListStyling();
        playListText0.style.backgroundColor = "rgba(0,0,0,0.06)";
        highlightPlayingTrack();
}
playListText1.onMouseDown= function () {
        removePlayListStyling();
        playListText1.style.backgroundColor = "rgba(0,0,0,0.06)";
        highlightPlayingTrack();
}
playListText2.onMouseDown= function () {
        removePlayListStyling();
        playListText2.style.backgroundColor = "rgba(0,0,0,0.06)";
        highlightPlayingTrack();
}
playListText3.onMouseDown= function () {
        removePlayListStyling();
        playListText3.style.backgroundColor = "rgba(0,0,0,0.06)";
        highlightPlayingTrack();
}
playListText4.onMouseDown= function () {
        removePlayListStyling();
        playListText4.style.backgroundColor = "rgba(0,0,0,0.06)";
        highlightPlayingTrack();
}
playListText5.onMouseDown= function () {
        removePlayListStyling();
        playListText5.style.backgroundColor = "rgba(0,0,0,0.06)";
        highlightPlayingTrack();
}
playListText6.onMouseDown= function () {
        removePlayListStyling();
        playListText6.style.backgroundColor = "rgba(0,0,0,0.06)";
        highlightPlayingTrack();
}
playListText7.onMouseDown= function () {
        removePlayListStyling();
        playListText7.style.backgroundColor = "rgba(0,0,0,0.06)";
        highlightPlayingTrack();
}
playListText8.onMouseDown= function () {
        removePlayListStyling();
        playListText8.style.backgroundColor = "rgba(0,0,0,0.06)";
        highlightPlayingTrack();
}
playListText9.onMouseDown= function () {
        removePlayListStyling();
        playListText9.style.backgroundColor = "rgba(0,0,0,0.06)";
        highlightPlayingTrack();
}
playListText10.onMouseDown= function () {
        removePlayListStyling();
        playListText10.style.backgroundColor = "rgba(0,0,0,0.06)";
        highlightPlayingTrack();
}
playListText11.onMouseDown= function () {
        removePlayListStyling();
        playListText11.style.backgroundColor = "rgba(0,0,0,0.06)";
        highlightPlayingTrack();
}
//=====================
// functions 
//=====================

//=====================
// functions to play a selected track when a playlist member is double-clicked
//=====================
playListText0.onMulticlick= function () {
// determine which track
 //print("chunkIndex " +chunkIndex );
    playIndex = 0 + (12 * chunkIndex) ;
    trackIndex = 0 ;
    startupFlg == 0;
    playOverride = false;
    PlayMedia(playIndex);
}
playListText1.onMulticlick= function () {
 //print("chunkIndex " +chunkIndex );
    playIndex = 1 + (12 * chunkIndex) ;
    trackIndex = 1 ;
    startupFlg = 0;
    playOverride = false;
    PlayMedia(playIndex);
}
playListText2.onMulticlick= function () {
    playIndex = 2 + (12 * chunkIndex) ;
    trackIndex = 2 ;
    startupFlg = 0;
    playOverride = false;
    PlayMedia(playIndex);
}
playListText3.onMulticlick= function () {
    playIndex = 3 + (12 * chunkIndex) ;
    trackIndex = 3 ;
    startupFlg = 0;
    playOverride = false;
    PlayMedia(playIndex);
}
playListText4.onMulticlick= function () {
    playIndex = 4 + (12 * chunkIndex) ;
    trackIndex = 4 ;
    startupFlg = 0;
    playOverride = false;
    PlayMedia(playIndex);
}
playListText5.onMulticlick= function () {
    playIndex = 5 + (12 * chunkIndex) ;
    trackIndex = 5 ;
    startupFlg = 0;
    playOverride = false;
    PlayMedia(playIndex);
}
playListText6.onMulticlick= function () {
    playIndex = 6 + (12 * chunkIndex) ;
    trackIndex = 6 ;
    startupFlg = 0;
    playOverride = false;
    PlayMedia(playIndex);
}
playListText7.onMulticlick= function () {
    playIndex = 7 + (12 * chunkIndex) ;
    trackIndex = 7 ;
    startupFlg = 0;
    playOverride = false;
    PlayMedia(playIndex);
}
playListText8.onMulticlick= function () {
    playIndex = 8 + (12 * chunkIndex) ;
    trackIndex = 8 ;
    startupFlg = 0;
    playOverride = false;
    PlayMedia(playIndex);
}
playListText9.onMulticlick= function () {
    playIndex = 9 + (12 * chunkIndex) ;
    trackIndex = 9 ;
    startupFlg = 0;
    playOverride = false;
    PlayMedia(playIndex);
}
playListText10.onMulticlick= function () {
    playIndex = 10 + (12 * chunkIndex) ;
    trackIndex = 10 ;
    startupFlg = 0;
    playOverride = false;
    PlayMedia(playIndex);
}
playListText11.onMulticlick= function () {
    playIndex = 11 + (12 * chunkIndex) ;
    trackIndex = 11 ;
    startupFlg = 0;
    playOverride = false;
    PlayMedia(playIndex);
}
//=====================
//End mouse multi click functions
//=====================

//===================================
//  function to remove play list scrolling
//===================================
function removePlayListScrolling() {
    if (debugFlg == 1) {print ("%-I-INFO, removePlayListScrolling")};

		// stop anything scrolling
        playListText0.scrolling = "off";
        playListText1.scrolling = "off";
        playListText2.scrolling = "off";
        playListText3.scrolling = "off";
        playListText4.scrolling = "off";
        playListText5.scrolling = "off";
        playListText6.scrolling = "off";
        playListText7.scrolling = "off";
        playListText8.scrolling = "off";
        playListText9.scrolling = "off";
        playListText10.scrolling = "off";
        playListText11.scrolling = "off";
}
//=====================
//End function
//=====================

//===================================
//  function to remove play list styling
//===================================
function removePlayListStyling() {
    if (debugFlg == 1) {print ("%-I-INFO, removePlayListStyling")};
        playListPage.style.backgroundColor = "rgba(255,255,255,0.06)";
// get rid of any background styling
        playListText0.style.backgroundColor = "transparent";
        playListText1.style.backgroundColor = "transparent";
        playListText2.style.backgroundColor = "transparent";
        playListText3.style.backgroundColor = "transparent";
        playListText4.style.backgroundColor = "transparent";
        playListText5.style.backgroundColor = "transparent";
        playListText6.style.backgroundColor = "transparent";
        playListText7.style.backgroundColor = "transparent";
        playListText8.style.backgroundColor = "transparent";
        playListText9.style.backgroundColor = "transparent";
        playListText10.style.backgroundColor = "transparent";
        playListText11.style.backgroundColor = "transparent";
}
//=====================
//End function
//=====================

//===================================
//  function to scroll individual items on the play list
//===================================
function scrollPlayList() {
    if (debugFlg == 1) {print ("%-I-INFO, scrollPlayList")};
// stop anything scrolling
        removePlayListScrolling();
        removePlayListStyling();
        highlightPlayingTrack();
}
//=====================
//End function
//=====================

//===================================
// set the play list tooltips
//===================================
function highlightPlayingTrack() {
    if (debugFlg == 1) {print ("%-I-INFO, highlightPlayingTrack")};
		if (playListfileCount==1) { //single file
			playListText0.scrolling = "left";
			playListText0.style.backgroundColor = "rgb(255,255,255)";;
		} else {
			// set the background styling for the selected track
			if (PlayIndex == 0+ (12 * chunkIndex)) {
			   playListText0.scrolling = "left";
			   playListText0.style.backgroundColor = "rgb(255,255,255)";;
			}
			if (PlayIndex == 1+ (12 * chunkIndex)) {
			   playListText1.scrolling = "left";
			   playListText1.style.backgroundColor = "rgb(255,255,255)";;
			}
			if (PlayIndex == 2+ (12 * chunkIndex)) {
                           playListText2.scrolling = "left";
			   playListText2.style.backgroundColor = "rgb(255,255,255)";;
			}
			if (PlayIndex == 3+ (12 * chunkIndex)) {
                           playListText3.scrolling = "left";
			   playListText3.style.backgroundColor = "rgb(255,255,255)";;
			}
			if (PlayIndex == 4+ (12 * chunkIndex)) {
                           playListText4.scrolling = "left";
			   playListText4.style.backgroundColor = "rgb(255,255,255)";;
			}
			if (PlayIndex == 5+ (12 * chunkIndex)) {
                           playListText5.scrolling = "left";
			   playListText5.style.backgroundColor = "rgb(255,255,255)";;
			}
			if (PlayIndex == 6+ (12 * chunkIndex)) {
                           playListText6.scrolling = "left";
			   playListText6.style.backgroundColor = "rgb(255,255,255)";;
			}
			if (PlayIndex == 7+ (12 * chunkIndex)) {
                           playListText7.scrolling = "left";
			   playListText7.style.backgroundColor = "rgb(255,255,255)";;
			}
			if (PlayIndex == 8+ (12 * chunkIndex)) {
                           playListText8.scrolling = "left";
			   playListText8.style.backgroundColor = "rgb(255,255,255)";;
			}
			if (PlayIndex == 9+ (12 * chunkIndex)) {
                           playListText9.scrolling = "left";
			   playListText9.style.backgroundColor = "rgb(255,255,255)";;
			}
			if (PlayIndex == 10+ (12 * chunkIndex)) {
                           playListText10.scrolling = "left";
			   playListText10.style.backgroundColor = "rgb(255,255,255)";;
			}
			if (PlayIndex == 11+ (12 * chunkIndex)) {
                           playListText11.scrolling = "left";
			   playListText11.style.backgroundColor = "rgb(255,255,255)";;
			}
		}
}
//=====================
//End function
//=====================


//===================================
//  function to select the previous page
//===================================
prevChunk.onMouseDown= function () {
  prevChunkClick();
}
//=====================
//End function
//=====================

//===================================
// function to handle the multiclick - this seems unnecessarily duplicated but it simply overrides the double click for the whole widget
//===================================
prevChunk.onMultiClick= function () {
  prevChunkClick();
}
//=====================
//End function
//=====================


//===================================
//  function to select the next page
//===================================
nextChunk.onMouseDown= function () {
  nextChunkClick();
}
//=====================
//End function
//=====================




//===========================================
// Function to slide the volume slider according to mouse scrollwheel position
//===========================================
function playlistFrameOnMouseWheel() {
	var delta = system.event.scrollDelta;
		if (delta > 0) {
			nextChunkClick();
		} else {
			prevChunkClick();
		}
}
//=====================
//End function
//=====================


//===================================
//  function to select the next page
//===================================
function nextChunkClick() {
    if (debugFlg == 1) {print ("%-I-INFO, nextChunkClick")};
                      trackIndex = 1;
                      chunkIndex = chunkIndex + 1;
		      if (debugFlg == 1) {print("chunkIndex "+chunkIndex)};
                      if (debugFlg == 1) {print("trackIndex "+trackIndex)};
                      updatePlayList();
}
//=====================
//End function
//=====================

//===================================
// function to handle the multiclick - this seems unnecessarily duplicated but it simply overrides the double click for the whole widget
//===================================
nextChunk.onMultiClick= function () {
  nextChunkClick();
}
//=====================
//End function
//=====================


//===================================
//  function to select the previous page
//===================================
function prevChunkClick() {
    if (debugFlg == 1) {print ("%-I-INFO, prevChunkClick")};
                      trackIndex = 1;
                      if (chunkIndex >0) {
                        chunkIndex = chunkIndex - 1;
						if (debugFlg == 1) {print("chunkIndex "+chunkIndex)};
						if (debugFlg == 1) {print("trackIndex "+trackIndex)};
                        updatePlayList();
                      }
}
//=====================
//End function
//=====================


//===================================
//  function to select the first page
//===================================
firstChunk.onMouseDown= function () {
    if (debugFlg == 1) {print ("%-I-INFO, firstChunk.onMouseDown")};
                        trackIndex = 1;
                        chunkIndex = 0;
						if (debugFlg == 1) {print("firstChunk chunkIndex "+chunkIndex)};
						if (debugFlg == 1) {print("firstChunk trackIndex "+trackIndex)};
                        updatePlayList();
}
//=====================
//End function
//=====================

//===================================
//  function to select the last page
//===================================
lastChunk.onMouseDown= function () {
    if (debugFlg == 1) {print ("%-I-INFO, lastChunk.onMouseDown")};
						if (debugFlg == 1) {print("playListfileCount "+playListfileCount)};
						if (debugFlg == 1) {print("idxFile "+idxFile)};

                        var totalChunks = idxFile / 12;
						if (debugFlg == 1) {print("totalChunks "+totalChunks)};
                        var intTotalPages = parseInt(totalChunks);
                        var tracks2 = 0;
                        if (totalChunks != intTotalPages) {
                                var tracks = totalChunks - intTotalPages;
                                tracks2 = parseInt((12 * tracks)+.49);
								if (debugFlg == 1) {print("No. of tracks to show = "+tracks2)};
                        }
                        //from this we can determine how many tracks to show on the last page
                        //if divisible by 11 then show the final 11 tracks on the page
                        //if not divisible by 11 then show the final tracks
                        // playListfileCount - tracks2
                        trackIndex = 1;
                        chunkIndex = totalChunks - 1;
                        updatePlayList();
}
//=====================
//End function
//=====================

//===================================
//  function to close the playlist
//===================================
redTap.onMouseDown= function () {
    if (debugFlg == 1) {print ("%-I-INFO, redTap.onMouseDown")};
    playlistFrame.visible = false;
}
//=====================
//End function
//=====================

//===================================
// function to make the buttons visible when the mouse is on the playlist
//===================================
playlistFrame.OnMouseEnter = function () {
    //if (debugFlg == 1) {print ("%-I-INFO, playlistFrame.OnMouseEnter")};
    buttonOpacity();
}
//=====================
//End function
//=====================


//===================================
// function to make the buttons visible when a mouseover event occurs
//===================================
function buttonOpacity() {
 //if (debugFlg == 1) {print ("%-I-INFO, buttonOpacity")};
 nextChunk.opacity = 255;
 prevChunk.opacity = 255;
 firstChunk.opacity = 255;
 lastChunk.opacity = 255;
 buttonConfig.opacity = 255; 
 oButton.opacity =255;
 sButton.opacity =255;
 ovalButton.opacity =255; 
}
//=====================
//End function
//=====================


//===================================
// function to fade the playlist buttons when the mouse is not on the playlist
//===================================
playlistFrame.onMouseExit = function () {
    //if (debugFlg == 1) {print ("%-I-INFO, playlistFrame.onMouseExit")};
    if ( preferences.playListKeysPref.value == "fade" ) {
       fadeTimer.ticking = true;
    }
}
//=====================
//End function
//=====================

//===================================
// function to handle multiclick on the chain pull
//===================================
chain.onMultiClick= function () {
     chainAction();               // this seems unnecessarily duplicated but it simply overrides the double click for the whole widget
}
//=====================
//End function
//=====================


//===================================
// function to handle a single click on the chain pull
//===================================
chain.onMouseDown= function () {
     chainAction();
}
//=====================
//End function
//=====================


//===================================
// function to animate the chain and activate the playlist
//===================================
function chainAction() {
    if (debugFlg == 1) {print ("%-I-INFO, chainAction")};
     chain.voffset = chain.voffset + (20 * Scale);
     sleep (100);
     //chain.voffset = chain.voffset - (20 * Scale);
     chain.voffset = chainvoffsetDefault * Scale;     
     // retained as the above voffset calculation is an approx. that causes placement problems

     if (playlistFrame.visible == true) {
        playlistFrame.visible = false;
		preferences.playListPref.value = "disabled";
     } else {
           playlistFrame.visible = true;
      	   preferences.playListPref.value = "enabled";
        // if the playlist needs to be refreshed
        if (chosenFolder == "") {
           chosenFolder = preferences.musicFolderPref.value;
		   if (debugFlg == 1) {print ("*****************chosenFolder " + chosenFolder)};
           //ReadFolderRecursively(chosenFolder );
           //updatePlayList();

		}
     }
 }
 //=====================
 //End function
 //=====================

 
 //=================================
// widget inline button timer setup
//=================================
var fadeTimer = new Timer();
fadeTimer.ticking = false;
fadeTimer.interval = 0.4;

//=================================
// busy icon timer setup
//=================================
var busyTimer = new Timer();
busyTimer.interval = 0.1;
busyTimer.ticking=false;
//=================================
// timers ends
//=================================


//=================================
// timer to fade the buttons
//=================================
fadeTimer.onTimerFired = function () {
	nextChunk.opacity = nextChunk.opacity - 5;
	prevChunk.opacity = nextChunk.opacity - 5;
	firstChunk.opacity = nextChunk.opacity - 5;
	lastChunk.opacity = nextChunk.opacity - 5;
	buttonConfig.opacity = buttonConfig.opacity - 5;
	oButton.opacity = oButton.opacity - 5;	
	sButton.opacity = sButton.opacity - 5;		
	ovalButton.opacity = ovalButton.opacity - 5;			
	if (nextChunk.opacity <= 0) { fadeTimer.ticking = false; }
};
//=================================
// timers ends
//=================================



//=====================
// the busy timer changes the busy icon
//=====================
busyTimer.onTimerFired = function () {
       busy.visible = true;
       busyBlur.visible = true;
       busyCounter = busyCounter + 1 ;
       if (busyCounter >= 7) {busyCounter = 1};
       busy.src = "Resources/busy-F" + busyCounter + "-32x32x24.png";
       //print("busyCounter " + busyCounter);
};
//=====================
//End function
//=====================


//=================================
// Function to open an XML file for reading
//=================================
function readSiteRecords() {
	if (debugFlg == 1) {print ("%-I-INFO, readSiteRecords")};
	chunkIndex = 0;
	var dict = [], i, filename, count = 0;
	isAudioCD = false;
	
		filename = chooseFile(".xml");
		var lines = filesystem.readFile(filename, true);
		
		// I should really read this properly but I hate parsing XML
		for (i = 0; i < 6; i += 1) {
			if (lines[i].substring(0,6) == "<path>") {				
				chosenFolder = lines[i].substring(6,lines[i].lastIndexOf("</path>"));
			}

			if (lines[i].substring(0,11) == "<filecount>") {				
			
				playListfileCount = (lines[i].substring(11,lines[i].lastIndexOf("</filecount>"))-1);
				log("found the playListfileCount "+ playListfileCount);
			}
		}
		log("chosenFolder "+ chosenFolder);

		thePlayList = new Array(playListfileCount);

		for (i = 0; i < lines.length; i += 1) {
			if (lines[i].substring(0,6) == "<file>") {
				//print("count] "+ count);
				
				thePlayList[count] = new FileMedia(lines[i].substring(6,lines[i].lastIndexOf("</file>")));
				//print("thePlayList[count].sourceURL  "+ thePlayList[count].sourceURL );	
				count = count + 1;
				//print("lines[i] "+ lines[i]);				

			}
		}
		
		log("----- readSiteRecords -----");

		//print("thePlayList[0].sourceURL  "+ thePlayList[0].sourceURL );	
		//print("thePlayList[8].sourceURL  "+ thePlayList[8].sourceURL );
		//print("thePlayList[playListfileCount-1].sourceURL  "+ thePlayList[playListfileCount-1].sourceURL );			
		
		//chosenFolder = f.substring(0,f.lastIndexOf("\/")+1);
		updatePlayList();
		alert('Playlist  "' + filename + '" read successfully.');
}
//=================================
// end function
//=================================



//=================================
// Function to open an XML file for writing
//=================================
function writeSiteRecords() {
	if (debugFlg == 1) {print ("%-I-INFO, writeSiteRecords")};
	var XMLpath = saveAs(), dict = [], i;

	var validSuffix = "xml";
	if (validSuffix.indexOf(xtn(XMLpath)) == -1 ) {
          alert("Invalid file type, please ensure your output file has .XML as the suffix.");
	  return;
        }

	if (XMLpath !== null) {
		if (xtn(XMLpath) === "") { XMLpath += ".xml"; }
		
		for (i = 0; i < thePlayList.length; i += 1) {
			dict[i] = {};
			
			dict[i].trackPath = convertPathToPlatform(thePlayList[i].sourceURL);
			//print("thePlayList[i] "+ thePlayList[i].sourceURL);
		}
		writeRecords(XMLpath, dict);
		
		//eprint("siteList.length: " + siteList.length);
		//eprint("siteList: " + siteList);
		log("----- writeSiteRecords -----");
		log(" ");
		alert('Playlist  "' + XMLpath + '" written successfully.');
		
	}
}
//=================================
// end function
//=================================


//=================================
// Function to write the records to a file
//=================================
function writeRecords(XMLpath, dict) {
	var i = 0,
	head = '<?xml version="1.0" encoding="UTF-8"?>\n<rss version="2.0">\n<channel>\n',
	tail = "</channel>\n</rss>\n",
	body = "";

	body += "<filecount>" + playListfileCount + "</filecount>\n";
	body += "<path>" + path + "</path>\n";

	for (i = 0; i < dict.length; i += 1) {
		body += "<file>" + dict[i].trackPath + "</file>\n";
	}
	filesystem.writeFile(XMLpath, head + body + tail);
}
//=================================
// end function
//=================================



//=================================
// Function to play a sound
//=================================
ovalButton.onMouseDown= function () {
	play(creturn, false);
}
//=================================
// end function
//=================================


//=================================
// Function to open a file
//=================================
oButton.onMouseDown= function () {
	readSiteRecords();

}
//=================================
// end function
//=================================


//=================================
// Function to open a file
//=================================
busy.onMouseDown= function () {
	busyStop();

}
//=================================
// end function
//=================================


//=================================
// Function to save a file
//=================================
sButton.onMouseDown= function () {
	writeSiteRecords();
}
//=================================
// end function
//=================================


//=================================
// Function to extract the extension from a filename string
//=================================
xtn = function (s) {
	var ext, idxFile = s.lastIndexOf(".");
	
	if (idxFile >= 0) {
		ext = s.substring(idxFile);
		if (ext.length > 7) { return ""; }
		if (ext.length > 1) { return ext; }
	}
	return "";
}
//=================================
// end function
//=================================





//=================================
// Function to
//=================================
speaker.onMouseUp=function() {
    openFolderToPlay();
}
//=================================
// end function
//=================================


//=================================
// Function to
//=================================
function openFolderToPlay() {
  if (preferences.soundpref.value === "enabled") {
     play(winding,true);
  }
  chosenFolder = chooseFolder("");     //YWE function

    path = chosenFolder;

    if (chosenFolder != "") {
       //print("chosenFolder "+chosenFolder);
       playerState = "folder"; //this is to ensure that shuffle mode is respected
       //  If it is a drive top folder chosen C:\ or d:\ for example
       if (chosenFolder.length == 3 && chosenFolder.substr(1,1) == ":")
       {
          var o = chosenFolder.substr(0,2);
          if (CDROMcount != 0 ) {
             if ( o == CDROM.Item(cdRomNo).driveSpecifier) {
               cdMenuItem.caption="Audio CD Drive ("+ CDROM.Item(cdRomNo).driveSpecifier +")"; //this line does nothing, it should..
               PlayAudioCD( 0 , CDROM.Item(cdRomNo).Playlist);
             } else {
                 alert("Player needs a folder not a drive root");
             }
          } else {
             alert("Player needs a folder not a drive root");
          }   
        } else { 
          ReadFolderRecursively(chosenFolder);
          saveFolder(chosenFolder);
          updatePlayList();
        }
     }
}
//=================================
// end function
//=================================



//=================================
// Function to
//=================================
widget.onUnload = function() {
    sliderTimer.enabled=false;
    positionTimer.enabled=false;
    WMPlayer = null;
}
//=================================
// end function
//=================================





//=================================
// Function unused, an Xwidget function that could be needed if WMP disconnects
//=================================
function wmpCheckCoreOnUpdate() // would need a timer to operate
{
   if (WMPlayer == null) {
     //  checking ActiveX access to the windows media player every 2 secs
     var WMPlayer = COM.createObject("wmplayer.ocx");
     COM.connectObject(WMPlayer, "WMP_");
     print("************IMPORTANT Widget reconnected WMPlayer.************");
     //alert("IMPORTANT Widget reconnected WMPlayer.");
  }
}
//=================================
// end function
//=================================



//=================================
// Function to clear the tooltips
//=================================
function clearPlayListHints()
{
                playListTitle.tooltip =  "";
		playListText0.tooltip =  "";
		playListText1.tooltip =  "";
		playListText2.tooltip =  "";
		playListText3.tooltip =  "";
		playListText4.tooltip =  "";
		playListText5.tooltip =  "";
		playListText6.tooltip =  "";
		playListText7.tooltip =  "";
		playListText8.tooltip =  "";
		playListText9.tooltip =  "";
		playListText10.tooltip =  "";
		playListText11.tooltip =  "";
}
//=================================
// end function
//=================================

/*

//===================================
// functions group to make the deletion taps appear
//===================================
deleteButton0.OnMouseEnter= function()
{
        deleteButton0.opacity=255;
}
deleteButton1.OnMouseEnter= function()
{
          deleteButton1.opacity=255;
}
deleteButton2.OnMouseEnter= function()
{
          deleteButton2.opacity=255;
}
deleteButton3.OnMouseEnter= function()
{
          deleteButton3.opacity=255;
}
deleteButton4.OnMouseEnter= function()
{
          deleteButton4.opacity=255;
}
deleteButton5.OnMouseEnter= function() 
{
          deleteButton5.opacity=255;
}
deleteButton6.OnMouseEnter= function() 
{
          deleteButton6.opacity=255;
}
deleteButton7.OnMouseEnter= function() 
{
          deleteButton7.opacity=255;
}
deleteButton8.OnMouseEnter= function() 
{
          deleteButton8.opacity=255;
}
deleteButton9.OnMouseEnter= function() 
{
          deleteButton9.opacity=255;
}
deleteButton10.OnMouseEnter= function() 
{
          deleteButton10.opacity=255;
}
deleteButton11.OnMouseEnter= function() 
{
          deleteButton11.opacity=255;
}
//=====================
//End functions group
//=====================






//===================================
// functions group to make the deletion taps disappear
//===================================

deleteButton0.onMouseExit= function() 
{
          deleteButton0.opacity=1;
}
deleteButton1.onMouseExit= function() 
{
          deleteButton1.opacity=1;
}
deleteButton2.onMouseExit= function() 
{
          deleteButton2.opacity=1;
}
deleteButton3.onMouseExit= function() 
{
          deleteButton3.opacity=1;
}
deleteButton4.onMouseExit= function() 
{
          deleteButton4.opacity=1;
}
deleteButton5.onMouseExit= function() 
{
          deleteButton5.opacity=1;
}
deleteButton6.onMouseExit= function() 
{
          deleteButton6.opacity=1;
}
deleteButton7.onMouseExit= function() 
{
          deleteButton7.opacity=1;
}
deleteButton8.onMouseExit= function() 
{
          deleteButton8.opacity=1;
}
deleteButton9.onMouseExit= function() 
{
          deleteButton9.opacity=1;
}
deleteButton10.onMouseExit= function() 
{
          deleteButton10.opacity=1;
}
deleteButton11.onMouseExit= function()
{
          deleteButton11.opacity=1;
}
//=====================
//End functions group
//=====================




//===================================
// function to delete a selected track
//===================================
function deleteTrack () {

}
//=====================
//End function
//=====================

*/




//======================================================================================
// END mediaPlayer.js
//======================================================================================


